package com.iteye.trafficRecorder;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class SensorHelper implements SensorEventListener {
	
	private SensorManager sensorManager;
	
	private float[] gravity = new float[3];
	
	private float[] geomagnetic = new float[3];
	
	//方位角度（正北为0， 正南为180）
	private float degree;
	
	//温度（°C）
	private float temperature;
	
	private boolean stop;
	
	//private float speed;
	
	public SensorHelper(Context context) {
		sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
		stop = true;
	}

	public void start() {
		if (stop) {
			stop = !stop;
			//注册温度传感器
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE), 
					SensorManager.SENSOR_DELAY_NORMAL);
			//注册速度传感器
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
					SensorManager.SENSOR_DELAY_NORMAL);
			sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), 
					SensorManager.SENSOR_DELAY_NORMAL);
		}
	}
	
	public void stop() {
		if (!stop) {
			stop = !stop;
			sensorManager.unregisterListener(this);
		}
	}
	
	private  void calculateOrientation() {
		float[] values = new float[3];
		float[] R = new float[16];
		float[] I = new float[16];
		SensorManager.getRotationMatrix(R, I, gravity, geomagnetic);
		SensorManager.getOrientation(R, values);
		degree = (float) Math.toDegrees(values[0]);
		//Log.d("", "degree=" + degree + ", temperature=" + temperature);
	}

	public void onSensorChanged(SensorEvent event) {
		switch (event.sensor.getType()) {
		case Sensor.TYPE_ACCELEROMETER :
			gravity = event.values;
			calculateOrientation();
			break;
		case Sensor.TYPE_MAGNETIC_FIELD :
			geomagnetic = event.values;
			calculateOrientation();
			break;
		case Sensor.TYPE_AMBIENT_TEMPERATURE :
			temperature = event.values[0];
			break;
		}
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		;
	}

	public float getDegree() {
		return degree;
	}

	public float getTemperature() {
		return temperature;
	}
	
	
}
